/* eslint-disable */
import Request from './request';
import {
	refreshToken
} from '@/api/login';
import indexConfig from '@/config/global.config.js';
import mUtil from '@/common/util.js';
import store from '@/store';

const http = new Request();

// request全局参数设置
http.setConfig(config => {
	/* 设置全局配置 */
	config.baseUrl = indexConfig.baseUrl; /* 根域名不同 */
	const systemInfo = uni.getSystemInfoSync();
	const systemInfoHeaders = {
		'device-name': systemInfo.brand, // 设备名称
		width: systemInfo.screenWidth, // 屏幕宽度
		height: systemInfo.screenHeight, // 屏幕高度
		os: systemInfo.platform, // 客户端平台
		'os-version': systemInfo.system // 操作系统版本
	};
	config.header = {
		...config.header,
		...systemInfoHeaders
	};
	return config;
});

let isRefreshing = false;
let requests = [];
http.interceptor.request(
	config => {

		if (config.isToken == false) {

		} else {
			config.header['token'] = uni.getStorageSync('token');
		}
		/* 请求之前拦截器 */

		// config.header['client'] = 'applet';
		config.header['client'] = 'app';
		// 单商户
		// config.header['merchant-id'] = uni.getStorageSync('merchantId') || 1;
		return config;
	},
	error => {
		return Promise.reject(error);
	}
);

// 刷新refreshToken
async function handleRefreshToken(refresh_token) {
	const params = {};
	params.group = mUtil.platformGroupFilter();
	params.refresh_token = refresh_token;
	await http.post(refreshToken, params).then(async r => {
		store.commit('login', r.data);
		isRefreshing = false;
	});
}
http.interceptor.response(
	async response => {
		/* 请求之后拦截器 */
		switch (response.data.code) {
			case 200:
				return response.data;
			case 400:
				mUtil.toast('错误的请求');
				return Promise.reject(response.data.message);
				break;
			case 50020:
			// uni.removeStorageSync('token');
			// uni.showModal({
			// 	content: '会话已过期，是否跳转登录页面？',
			// 	success: confirmRes => {
			// 		if (confirmRes.confirm) {
			// 			uni.reLaunch({
			// 				url:'/pages/research/register/login'
			// 			})
			// 		}
			// 	}
			// });
			case 50000:
				isRefreshing = false;
				if (response.config.url === refreshToken) {
					uni.removeStorageSync('token');
					await store.commit('logout');
					uni.showModal({
						content: '会话已过期，是否跳转登录页面？',
						success: confirmRes => {
							if (confirmRes.confirm) {
								uni.navigateTo({
									url: '/pages/research/register/login'
								})
							}
						}
					});
					break;
				} else {
					let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
					let curRoute = routes[routes.length - 1].route // 获取当前页面路由，也就是最后一个打开的页面路由
					// 如果refreshToken为空 则直接跳转登录
					console.log('token:' + store.state.refreshToken)
					if (!store.state.refreshToken) {
						uni.removeStorageSync('token');
						await store.commit('logout');
						// uni.showModal({
						// 	content: '会话已过期，是否跳转登录页面？',
						// 	// showCancel: false,
						// 	success: confirmRes => {
						// 		if (confirmRes.confirm) {
						// 			uni.reLaunch({
						// 				url:'/pages/research/register/login'
						// 			})

						// 		}
						// 	}
						// });
						if (curRoute != 'pages/index/personal') {
							uni.navigateTo({
								url: "/pages/research/register/login"
							})
						}
						throw response.data.message;
					} else {
						// isRefreshing同一个页面只执行一次
						if (!isRefreshing) {
							isRefreshing = true;
							// 刷新token
							await handleRefreshToken(store.state.refreshToken, response);
							requests.forEach(cb => cb());
							requests = [];
							isRefreshing = false;
							return http.request(response.config);
						} else {
							return new Promise(resolve => {
								// 将resolve放进队列，用一个函数形式来保存，等token刷新后直接执行
								requests.push(() => {
									resolve(http.request(response.config));
								});
							});
						}
					}
				}
				break;
			case 20041:
				mUtil.toast(response.data.msg);
				// setTimeout(()=>{
				// 	uni.navigateBack({
				// 		delta:1
				// 	})
				// },1000)
				return
			case 20047:
				mUtil.toast(response.data.msg);
				// setTimeout(()=>{
				// 	uni.navigateBack({
				// 		delta:1
				// 	})
				// },1000)
				return
			case 20049:
				mUtil.toast(response.data.msg);
				// setTimeout(()=>{
				// 	uni.navigateBack({
				// 		delta:1
				// 	})
				// },1000)
				return
			case 20050:
				mUtil.toast(response.data.msg);
				// setTimeout(()=>{
				// 	uni.navigateBack({
				// 		delta:1
				// 	})
				// },1000)
				return
			case 20022:
				mUtil.toast(response.data.msg);
				// setTimeout(()=>{
				// 	uni.navigateBack({
				// 		delta:1
				// 	})
				// },1000)
				return
			case 20057:
				mUtil.toast(response.data.msg);
				// setTimeout(()=>{
				// 	uni.navigateBack({
				// 		delta:1
				// 	})
				// },1000)
				return
			case 20058:
				mUtil.toast(response.data.msg);
				// setTimeout(()=>{
				// 	uni.navigateBack({
				// 		delta:1
				// 	})
				// },1000)
				return
			case 50028:
				mUtil.toast(response.data.msg);
				// setTimeout(()=>{
				// 	uni.navigateBack({
				// 		delta:1
				// 	})
				// },1000)
				return
			case 99999:
				mUtil.toast(response.data.msg);
				setTimeout(() => {
					mUtil.getCurrentPageFun('/pages/research/pay-password')
				}, 1000)
				return
			case 405:
				mUtil.toast(response.data.msg);
				return Promise.reject(response.data.msg);
			case 404:
				mUtil.toast(response.data.msg);
				return Promise.reject(response.data.msg);
			case 429:
				mUtil.toast(response.data.msg);
				return Promise.reject(response.data.msg);
			case 500:
				if (response.data.code == 500 && response.data.msg == '请更新最新版本登录') {
					uni.showModal({
						title: '提示',
						content: response.data.msg,
						cancelText: "取消", // 取消按钮的文字  
						confirmText: "确认", // 确认按钮的文字  
						showCancel: true, // 是否显示取消按钮，默认为 true
						confirmColor: '#FF721B',
						cancelColor: '#9B9B9B',
						success: (res) => {
							if (res.confirm) {
								if (plus.os.name == "Android") {
									// 跳转安卓应用市场
									let appurl = "market://details?id=com.juhe.chainfinancial" //这个是通用应用市场，如果想指定某个应用商店，需要单独查这个应用商店的包名或scheme及参数
									plus.runtime.openURL(appurl)
								} else {
									// 跳转AppStore
									let appleId = 6449833699
									plus.runtime.launchApplication({
										action: `itms-apps://itunes.apple.com/cn/app/id${appleId}`,
									})
								}
							} else {
								console.log('cancel') //点击取消之后执行的代码
							}
						}
					})
				} else {
					mUtil.toast(response.data.msg);
				}
				return Promise.reject(response.data.msg);

			default:
				mUtil.toast(response.data.msg);
				return Promise.reject(response.data.msg);
		}
	},
	error => {
		return Promise.reject(error);
	}
);

export {
	http
};
